package com.lagou.rpc.client.handler;

import com.lagou.common.util.RpcRequest;
import com.lagou.common.util.RpcService;
import com.lagou.common.zk.ServiceCenter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.Data;

import java.sql.Timestamp;
import java.util.concurrent.Callable;

@Data
public class UserClientHandler extends ChannelInboundHandlerAdapter implements Callable {

    private ChannelHandlerContext context;
    private String result;
    private RpcRequest rpcRequest;
    private RpcService rpcService;

    @Override
    public void channelActive(ChannelHandlerContext context) {
        this.context = context;
    }

    /**
     * 收到服务端数据，唤醒等待线程
     */
    @Override
    public synchronized void channelRead(ChannelHandlerContext context, Object msg) {
        result = msg.toString();
        notify();
    }

    /**
     * 写出数据，开始等待唤醒
     */
    @Override
    public synchronized Object call() throws Exception {

        Timestamp startTime = new Timestamp(System.currentTimeMillis());

        context.writeAndFlush(rpcRequest);
        wait();

        Timestamp endTime = new Timestamp(System.currentTimeMillis());

        // Zookeeper记录每个服务端的最后一次响应时间
        ServiceCenter.updateServiceResponseTime(rpcService, endTime.getTime() - startTime.getTime());

        return result;
    }
}
